package org.obsidianrad.server.services.obj2db.decisioners;


import org.obsidianrad.server.services.ObsModel;
import org.obsidianrad.server.services.user.rolemanager.RoleManager;
import org.obsidianrad.utils.Constant.ObsidianOperations;
import org.springframework.security.Authentication;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.context.SecurityContextHolder;

public class DecisionerImpl implements IDecisioner {

	private RoleManager roleManager;
	
	/* (non-Javadoc)
	 * @see org.obsidianrad.server.services.obj2db.decisioners.IDecisioner#decide(org.obsidianrad.utils.Constant.ObsidianOperations, java.lang.String)
	 */
	public boolean decide(ObsidianOperations op, String reference){

		// result.setDetails( ((ObsidianUserDetails)user).getPreferences() );
		
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); // UsernamePasswordAuthenticationToken

		if(authentication.getName().equals("admin")){
			return true;
		}
		
		GrantedAuthority[] authorities = authentication.getAuthorities();

		// costruisci il ruolo richiesto
		String requestedRole = roleManager.constructRole(reference, op);
		
		// controlla se il ruolo costruito esiste per questo utente, nella lista dei ruoli abilitati
		for(GrantedAuthority auth : authorities){
			if(auth.getAuthority().equals(requestedRole)){
				return true;
			}
		}

		return false;
	}

	/* (non-Javadoc)
	 * @see org.obsidianrad.server.services.obj2db.decisioners.IDecisioner#decide(org.obsidianrad.utils.Constant.ObsidianOperations, java.lang.Class)
	 */
	public boolean decide(ObsidianOperations op, Class<? extends ObsModel> reference){
		return decide(op, reference.getCanonicalName());
	}
	
	public RoleManager getRoleManager() {
		return roleManager;
	}

	public void setRoleManager(RoleManager roleManager) {
		this.roleManager = roleManager;
	}
}
